<template>
    <div class="fileImport" ref="fileImport">
        <el-dialog v-model="importVisible" :title="'导入'" width="576px" @close="closeImport">
            <div class="flex-center" style="align-items: center;">
                <div style="padding-bottom:10px"
                    class="margin-l-r-15px gary-border text-center padding-20px fileImportItem">
                    <span>{{ props.importItem.downTitle || '1、模板下载' }}</span>
                    <img :src="excelImport" alt="">
                    <el-button type="primary" @click="fileDown">{{ props.importItem.downButtonText || '下 载' }}</el-button>
                </div>
                <div class="margin-l-r-15px gary-border text-center padding-20px fileImportItem">
                    <span>{{ props.importItem.upTitle || '2、表格上传' }}</span>
                    <img :src="word" alt="">
                    <el-upload v-model:file-list="fileList" ref="uploadRef"  accept=".xls,.xlsx" class="upload-demo" :action="uploadFileUrl" multiple
                        :show-file-list="false" :headers="headers" :on-preview="handlePreview" :on-remove="handleRemove"
                        :on-success="onSuccess" :on-error="onError" :before-upload="beforeUpload"
                        :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed">
                        <el-button>{{ props.importItem.downButtonText || '上 传' }}</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                <!-- jpg/png files with a size less than 500KB. -->
                            </div>
                        </template>
                    </el-upload>
                </div>
            </div>
        </el-dialog>
        <el-dialog title="数据导入返回结果" v-model="resultVisible"  @close="closeResult">
            <div class="consequence">
                <div class="consequence-item flex">
                    <SuccessFilled style="width:16px;height:16px;color:#409eff" />
                    <span class="margin-l-10px">{{ Amount.successAmount }}条记录导入成功</span>
                </div>
                <div class="consequence-item flex  margin-t-b-20px">
                    <CircleCloseFilled style="width:16px;height:16px;color:#f56c6c" />
                    <span class="margin-l-10px">{{ Amount.failAmount }}条记录导入失败</span>
                </div>
            </div>
            <div>
                <el-table :data="resultData" :header-cell-style="{ 'text-align': 'center', 'background': '#fff', 'height': '44px' }"
                    :cell-style="{ 'text-align': 'center', 'height': '44px' }" style="max-height:440px;overflow-y: scroll">
                    <el-table-column label="行号" prop="orderNum"></el-table-column>
                    <!-- <el-table-column label="名称" prop="content"></el-table-column> -->
                    <el-table-column label="失败原因" prop="message"></el-table-column>
                </el-table>
            </div>
            <template #footer>
                <span class="dialog-footer " style="display: block;transform: translateY(20px); ">
<!--                    <el-button @click="resultVisible = false">取 消</el-button>-->
                    <el-button type="primary" @click="resultVisible = false, emit('successResult', resultData)">确
                        定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import excelImport from '@/assets/images/excelImport2.png'
import word from '@/assets/images/word2.png'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from "@/utils/auth";
import { download } from "@/utils/request";
const { proxy } = getCurrentInstance();
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const props = defineProps({
    importVisible: { default: false },
    importItem: {
        default: function () {
            return {
                downUrl: '',
                upUrl: '',
                fileDown() { },
                downTitle: '',
                downButtonText: '',
                upButtonText: '',
                upTitle: '',
                blob: false,
            }
        }
    },
})
const emit = defineEmits(['update:importVisible', 'onSuccess', 'onError', 'fileDown', 'successResult'])
const Amount = reactive({
    successAmount: 0,
    failAmount: 0
})
const resultData = ref([])
const importVisible = ref(false)
const resultVisible = ref(false)
const fileList = ref([])
watch(() => props.importVisible, () => {
    importVisible.value = props.importVisible
})
onMounted(() => {
    if (props.importItem.upUrl) {
        uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + props.importItem.upUrl
    }
})
const closeImport = () => { clearFileList(); emit("update:importVisible", false) }
const fileDown = () => {
    if (props.importItem.blob) {
        download(props.importItem.downUrl, {}, props.importItem.downName || '导入模板', {}, {})
        return
    }
    props.importItem.downUrl ? location.href = props.importItem.downUrl : props.importItem.fileDown || emit('fileDown')
}
// 上传前
const beforeUpload = () => { ElMessage.success('文件上传中，请耐心等待') }
const onSuccess = (uploadFile, uploadFiles) => {
    emit('onSuccess', uploadFile)
    setTimeout(() => {
        ElMessage.success(uploadFile.msg || '文件上传成功');
        Amount.successAmount = uploadFile.data.successAmount
        Amount.failAmount = uploadFile.data.errorAmount
        resultData.value = uploadFile.data.errorList
        resultVisible.value = true
    }, 300)
}
const onError = (uploadFile, uploadFiles) => {
    emit('onError', uploadFile)
    setTimeout(() => {
        ElMessage.warning(uploadFile.msg || '文件上传失败');
    }, 300)
}
const handleRemove = (file, uploadFiles) => {
    console.log(file, uploadFiles)
}
const handlePreview = (uploadFile) => {
    console.log(uploadFile)
}
const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
      `导入限制1个文件`
  )
    // ElMessage.warning(
    //     `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    //     } totally`
    // )
}
const beforeRemove = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `确定移出${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}

const clearFileList = () => {
  fileList.value = [];
  proxy.$refs["uploadRef"].clearFiles()
};

function closeResult() {
  clearFileList()
  resultVisible.value = false
  importVisible.value = false
}


</script>

<style lang="scss" scoped>
:deep(.el-dialog:not(.is-fullscreen)) {
    width: 556px;
    padding-bottom: 30px;
}

.fileImportItem {
    width: 233px;
    height: 211px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;

    span {
        color: rgb(153, 153, 153);
    }

    img {
        margin: 25px;
        width: 60px;
        height: 70px;
    }
}

:deep(.el-dialog__header) {
    text-align: center;

    span {
        font-size: 18px;
    }
}

.consequence {
    .consequence-item {}
}
</style>
